package com.kai.mqtt.statistics.impl;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
import com.kai.mqtt.statistics.IStatisticsService;
import com.kai.mqtt.data.response.LatestDataResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author weijk
 * @since 2024/7/4
 */
@Service
public class StatisticsServiceImpl implements IStatisticsService {

    private static final AtomicInteger MSG_INFLOW = new AtomicInteger(0);

    private static final AtomicInteger MSG_OUTFLOW = new AtomicInteger(0);

    private static final Cache<LocalDateTime, LatestDataResponse> CACHE = CacheBuilder.newBuilder()
            .expireAfterWrite(86400, TimeUnit.SECONDS)
            .initialCapacity(1000)
            .maximumSize(87000)
            .build();

    private static LocalDateTime LAST_KEY = null;

    /**
     * 获取流入消息并重置为 0
     *
     * @return 流入消息
     */
    @Override
    public Integer getMsgInflow() {
        return MSG_INFLOW.getAndSet(0);
    }

    /**
     * 获取流出消息并重置为 0
     *
     * @return 流出消息
     */
    @Override
    public Integer getMsgOutflow() {
        return MSG_OUTFLOW.getAndSet(0);
    }

    /**
     * 增加流入消息
     */
    @Override
    public void incrementMsgInflow() {
        MSG_INFLOW.incrementAndGet();
    }

    /**
     * 增加流出消息
     */
    @Override
    public void incrementMsgOutflow() {
        MSG_OUTFLOW.incrementAndGet();
    }

    /**
     * 保存新数据
     *
     * @param latestDataResponse 新数据
     */
    @Override
    public void put(LatestDataResponse latestDataResponse) {
        CACHE.put(latestDataResponse.getDateTime(), latestDataResponse);
        LAST_KEY = latestDataResponse.getDateTime();
    }

    /**
     * 获取最新一条数据
     *
     * @return 新数据
     */
    @Override
    public LatestDataResponse getLatestData() {
        return getValue(LAST_KEY);
    }

    private LatestDataResponse getValue(LocalDateTime key) {
        try {
            return CACHE.get(key, () -> new LatestDataResponse()
                    .setMsgInflow(0)
                    .setMsgOutflow(0)
                    .setConnect(0)
                    .setOnlineConnect(0)
                    .setTopics(0)
                    .setSubscriptions(0)
                    .setDateTime(key));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取最新时间段内数据列表
     *
     * @param latest 最近时间（秒）
     * @return 数据列表
     */
    @Override
    public List<LatestDataResponse> listLatestData(Integer latest) {
        LocalDateTime localDateTime = LocalDateTime.now().withNano(0);
        int remainder = localDateTime.getSecond() % 10;
        localDateTime = localDateTime.minusSeconds(remainder == 0 ? 10 : remainder);

        List<LatestDataResponse> responses = Lists.newArrayList();
        for (int i = latest; i > 0; i -= 10) {
            LatestDataResponse latestDataResponse = getValue(localDateTime.minusSeconds(i));
            Integer msgInflow = latestDataResponse.getMsgInflow();
            Integer msgOutflow = latestDataResponse.getMsgOutflow();
            LocalDateTime dateTime = latestDataResponse.getDateTime();
            for (int j = 1; j < 10; j++) {
                LatestDataResponse latestData = getValue(dateTime.minusSeconds(j));
                msgInflow += latestData.getMsgInflow();
                msgOutflow += latestData.getMsgOutflow();
            }

            LatestDataResponse response = new LatestDataResponse();
            BeanUtils.copyProperties(latestDataResponse, response);
            response.setMsgInflow(msgInflow)
                            .setMsgOutflow(msgOutflow);

            responses.add(response);
        }

        return responses;
    }
}
